<template>
  <el-select
    v-model="sup_id"
    size="small"
    :remote-method="selSups"
    remote
    filterable
    style="width: 100%"
    placeholder="请选择供应商"
    clearable
    @change="selChange"
    @focus="selSups"
  >
    <el-option
      v-for="item in suppliers"
      :key="item.key"
      :label="item.value"
      :value="item.key"
    />
  </el-select>
</template>

<script>
import { querySupplier, selSups } from '@/api/supplier'

export default {
  name: 'SupplierSelectObject',
  props: {
    value: {
      type: Object,
      default: null
    },
    id: {
      type: String,
      default: null
    }
    
  },
  data() {
    return {
      suppliers: [],
      supplier: {},
      sup_id: null
    }
  },
  watch: {
    'sup_id': {
      handler(n, o) {
        if (this.sup_id && this.sup_id !== '') {
          this.querySupplier()
        }
      },
      immediate: false
    },
    'id': {
      handler(n, o) {
        if (this.id && this.id !== '') this.$set(this, 'sup_id', this.id)
      },
      immediate: false
    }
  },
  created() {
    if (this.id && this.id !== '') this.$set(this, 'sup_id', this.id)
  },
  methods: {
    selChange() {
      if(this.sup_id === '') {
        this.$emit('input', {})
      }else {
        const len = this.suppliers.length
        let i = 0
        for (i = 0; i < len; i++) {
          if (this.suppliers[i]['key'] === this.sup_id) {
            this.supplier = this.suppliers[i]
            break
          }
        }
        this.$emit('input', this.supplier)
      }
    },
    selSups(query) {
      let str = ''
      if (Object.prototype.toString.call(query) === '[object String]') str = query
      selSups({ name: str }).then(response => {
        this.suppliers = response.list
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    querySupplier() {
      this.$set(this, 'suppliers', [])
      querySupplier({ id: this.sup_id }).then(response => {
        const info = {}
        info.key = response.info.id
        info.value = response.info.name
        this.suppliers.push(info)
        this.selChange()
      }).catch(err => {
        this.$message.error(err.msg)
      })
    }
  }
}
</script>

<style scoped>
</style>
